﻿<div id="time-line-script">
    <!-- 添加触发事件的弹窗 -->
    <el-dialog v-model="visible" style="--el-dialog-margin-top:8vh" title="添加触发事件" width="1000" @close="handleAddTimeClose">
        <el-form label-width="auto" style="width:100%;">
            <el-form-item label="脚本名称" required>
                <el-input v-model="scriptTitle" clearable class="form-item-input"></el-input>
            </el-form-item>
            <el-form-item label="触发时间" required>
                <el-time-picker v-model="scriptTime"
                    :disabled-hours="disabledHours"
                    :disabled-minutes="disabledMinutes"
                    :disabled-seconds="disabledSeconds"
                    clearable></el-time-picker>
            </el-form-item>
            <el-form-item label="试题" required>
                <div class="question-list-edit">
                    <el-card style="margin-bottom: 8px;" v-for="(question, index) in questionList" :key="question.key">
                        <template #header>
                            <div class="card-header">题{{index+1}}</div>
                        </template>
                        <div class="question-row">
                            <div class="questions">
                                <el-form-item label="题型" required>
                                    <el-select v-model="question.QType">
                                        <el-option v-for="item in QType"
                                            :key="item.value"
                                            :label="item.label"
                                            :value="item.value" />
                                    </el-select>
                                </el-form-item>
                                <el-form-item label="题目" style="margin-top: 10px;" required>
                                    <el-upload v-model:file-list="question.Question"
                                        action="/ApiFilter/UploadFiles.ashx"
                                        list-type="picture-card"
                                        accept="image/*"
                                        :on-success="(response, uploadFile) => uploadQuestionImgSuc(question, response, uploadFile)"
                                        :on-preview="(uploadFile) => handlePictureCardPreview(question.Question, uploadFile)"
                                        :on-remove="handleQuestionRemove">
                                        <el-icon><plus></plus></el-icon>
                                    </el-upload>
                                </el-form-item>
                                <el-form-item label="答案" style="margin-top: 10px;" required>
                                    <el-upload v-model:file-list="question.Answer"
                                        action="/ApiFilter/UploadFiles.ashx"
                                        list-type="picture-card"
                                        accept="image/*"
                                        :on-success="(response, uploadFile) => uploadAnswerImgSuc(question, response, uploadFile)"
                                        :on-preview="(uploadFile) => handlePictureCardPreview(question.Answer, uploadFile)"
                                        :on-remove="handleAnswerRemove">
                                        <el-icon><plus></plus></el-icon>
                                    </el-upload>
                                </el-form-item>
                            </div>
                            <div class="question-options">
                                <el-button type="primary" @click="handleAddQuestion(question)" plain size="small" icon="CirclePlus">添加</el-button>
                                <el-popconfirm v-if="questionList.length>1" title="你确定要移除此题吗？" placement="top-start" @confirm="handleRemoveQuestion(question)">
                                    <template #reference>
                                        <el-button type="danger" plain size="small" icon="Remove">移除</el-button>
                                    </template>
                                </el-popconfirm>
                            </div>
                        </div>
                    </el-card>
                </div>
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="handleAddTimeClose">取 消</el-button>
                <el-button type="primary" @click="handleAddTimeSaveData">保 存</el-button>
            </div>
        </template>
    </el-dialog>
</div>
<script>
    createApp({
        el: '#time-line-script',
        data() {
            return {
                // 弹窗始终打开
                visible: true,
                // 脚本id
                timeId: '',
                // 视频ID
                videoId: '',
                // 操作类型：add-新增，edit-编辑
                option: '',
                // 弹窗标题
                dialogTitle: '',
                // 脚本名称
                scriptTitle: '',
                // 脚本触发时间
                scriptTime: '',
                // 题目列表
                questionList: [],
                // 题型
                QType: [
                    { value: 1, label: '选择题' },
                    { value: 2, label: '简答题' }
                ]
            }
        },
        mounted() {
            this.initQuestionList();
        },
        methods: {
            // 秒换算：秒 -> 时分秒
            formatSecondsToHMS(seconds) {
                const hrs = Math.floor(seconds / 3600);
                const mins = Math.floor((seconds % 3600) / 60);
                const secs = Math.floor(seconds % 60);

                return {
                    hours: hrs,
                    minutes: mins,
                    seconds: secs
                };
            },
            // number 范围填充
            makeRange(start, end) {
                const result = []
                for (let i = start; i <= end; i++) {
                    result.push(i)
                }
                return result
            },
            // 时间可选项限制：小时
            disabledHours() {
                const maxHms = this.formatSecondsToHMS(Math.floor(this.pageQuery.player.duration));
                if (maxHms.hours > 23) return [];
                if (maxHms.hours === 23) return [24];
                return this.makeRange(maxHms.hours + 1, 24);
            },
            // 时间可选项限制：分钟
            disabledMinutes(hour) {
                const maxHms = this.formatSecondsToHMS(Math.floor(this.pageQuery.player.duration));
                // 没考虑超过24小时的情况
                if (hour === maxHms.hours) {
                    if (maxHms.minutes === 60) return [];
                    if (maxHms.minutes === 59) return [60];
                    return this.makeRange(maxHms.minutes + 1, 60)
                }
            },
            // 时间可选项限制：秒
            disabledSeconds(hour, minute) {
                const maxHms = this.formatSecondsToHMS(Math.floor(this.pageQuery.duration));
                // 没考虑超过24小时的情况
                if (hour === maxHms.hours && minute === maxHms.minutes) {
                    if (maxHms.seconds === 60) return [];
                    if (maxHms.seconds === 59) return [60];
                    return this.makeRange(maxHms.seconds + 1, 60)
                }
            },
            // 初始化题目列表
            initQuestionList() {
                this.option = this.pageQuery.option;
                this.timeId = this.pageQuery.timeId;
                this.videoId = this.pageQuery.videoId;
                // 根据 player.currentTime 算出当前的时分秒
                const hms = this.formatSecondsToHMS(Math.floor(this.pageQuery.scriptTime || 0));
                // 初始化时间，这里的年月日不重要，我们只需要时分秒
                const tempTime = new Date(2025, 11, 17, hms.hours, hms.minutes, hms.seconds);
                this.scriptTime = tempTime;
                this.scriptTitle = this.pageQuery.scriptTitle;

                if (this.option === 'add') {
                    this.questionList = [
                        {
                            key: guid(),
                            QType: 1,
                            Question: [],
                            Answer: []
                        }
                    ]
                }

                if (this.option === 'edit') {
                    // 获取数据
                    ktlapi({
                        action: 'Cus_GetMathCourseVideoTimeQuestionList',
                        data: {
                            TimeId: this.pageQuery.timeId
                        }
                    }).then(resp => {
                        const list = resp.data || [];
                        list.forEach(item => {
                            item.key = guid();
                            if (item.Question) {
                                item.Question = JSON.parse(item.Question);
                            }
                            if (item.Answer) {
                                item.Answer = JSON.parse(item.Answer);
                            }
                        })
                        console.log('list', list)
                        this.questionList = list || [];
                    })
                }
            },
            handleAddQuestion(question) {
                const findIndex = this.questionList.findIndex(item => item.key === question.key);
                this.questionList.splice(findIndex + 1, 0, {
                    key: guid(),
                    QType: 1,
                    Question: [],
                    Answer: []
                })
            },
            handleRemoveQuestion(question) {
                const findIndex = this.questionList.findIndex(item => item.key === question.key);
                this.questionList.splice(findIndex, 1);
            },
            /** 上传题目图片 */
            uploadQuestionImgSuc(question, response, uploadFile) {
                uploadFile.url = SERVER_HOST + response[0]["file"]
            },
            /** 上传答案图片 */
            uploadAnswerImgSuc(question, response, uploadFile) {
                uploadFile.url = SERVER_HOST + response[0]["file"]
            },
            /** 删除题目图片 */
            handleQuestionRemove(data) {
                console.log('handleQuestionRemove', data)
            },
            /** 删除答案图片 */
            handleAnswerRemove(data) {
                console.log('handleQuestionRemove', data)
            },
            /** 预览图片 */
            handlePictureCardPreview(fileList, uploadFile) {
                console.log('uploadFile', uploadFile)
            },
            handleAddTimeClose() {
                this.sendEmit({ action: 'close' })
            },
            formatCommitData(question) {
                return {
                    ...(this.option === 'edit' ? { ID: question.ID || 0 } : {} ),
                    QType: question.QType,
                    Question: question.Question.map(item => ({ uid: item.uid, url: item.url, name: item.name })),
                    Answer: question.Answer.map(item => ({ uid: item.uid, url: item.url, name: item.name })),
                }
            },
            handleAddTimeSaveData() {
                if (isEmpty(this.scriptTitle, true)) {
                    Notify.error("请填写脚本名称");
                }

                // 此处需要进行数据校验
                if (this.questionList.length === 0) {
                    Notify.error("请上传题目");
                    return;
                }
                // 获取有效的题
                const validQuestionList = this.questionList.filter(item => item.Question.length > 0 && item.Answer.length > 0);
                if (validQuestionList.length === 0) {
                    Notify.error("请完善题目与答案");
                    return;
                }

                // 处理时间，转换为秒
                const currHMS = dateFormat(this.scriptTime, 'hh:mm:ss');
                const timeSp = currHMS.split(':');
                const hours = Number(timeSp[0]);
                const minutes = Number(timeSp[1]);
                const seconds = Number(timeSp[2]);
                const countSeconds = seconds + minutes * 60 + hours * 60 * 60;

                // 格式化题目数据对象
                const formatQuestionList = validQuestionList.map(item => this.formatCommitData(item))

                if (this.option === 'add') {
                    ktlapi({
                        action: 'Cus_AddMathCourseVideoQuestion',
                        data: {
                            VideoId: this.videoId,
                            Title: this.scriptTitle,
                            Time: countSeconds,
                            QuestionList: JSON.stringify(formatQuestionList)
                        }
                    }).then(resp => {
                        Notify.success("保存成功");
                        this.sendEmit({ action: 'refresh' })
                    })
                }

                if (this.option === 'edit') {
                    ktlapi({
                        action: 'Cus_UpdateMathCourseVideoQuestion',
                        data: {
                            TimeId: this.timeId,
                            Title: this.scriptTitle,
                            Time: countSeconds,
                            QuestionList: JSON.stringify(formatQuestionList)
                        }
                    }).then(resp => {
                        Notify.success("保存成功");
                        this.sendEmit({ action: 'refresh' })
                    })
                }

                
            },
        }
    })
</script>